from django.contrib.gis.db import models
from django.contrib.auth.models import User

import datetime
from decimal import Decimal

REJSEPLANEN_URL = 'http://xmlopen.rejseplanen.dk/bin/rest.exe'


class GPSLog(models.Model):
  user = models.ForeignKey(User)
  x = models.IntegerField("Longitude", max_length=255)
  y = models.IntegerField("Latitude", max_length=255)
  geom = models.GeometryField(srid=4326, null=True) 
  timestamp = models.DateTimeField("DateTime")
  time = models.TimeField("Time")
  location = models.ForeignKey('Location', null=True)

  objects = models.GeoManager()

  def _convert(self, number):
    return str(Decimal(number)/1000000)

  @property
  def longitude(self):
    return self._convert(self.x)

  @property
  def latitude(self):
    return self._convert(self.y)

  def save(self, *args, **kwargs):
    if not self.id:
      if not self.timestamp:
        self.timestamp = datetime.datetime.now()
    return super(GPSLog, self).save(*args, **kwargs)


class ErrorReport(models.Model):
  user = models.ForeignKey(User, null=True, blank=True)
  tag = models.CharField("Tag", max_length=255)
  message = models.TextField("Message")
  created = models.DateTimeField("Created", auto_now_add=True)


class Location(models.Model):
  user   = models.ForeignKey(User)
  x      = models.IntegerField("Longitude")
  y      = models.IntegerField("Latitude")
  geom   = models.GeometryField(srid=4326)
  radius = models.IntegerField("Radius")
  count  = models.IntegerField("Point count")

  objects = models.GeoManager()

  def __unicode__(self):
    return "x:%f y:%f" % (self.geom.get_x(), self.geom.get_y())

class LogGroup(models.Model):
  user     = models.ForeignKey(User)
  day_part = models.IntegerField("Part of day")
  date     = models.DateField("Date")
  location = models.ForeignKey(Location)



